import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/lunar_data.dart';

class LunarInfoCard extends StatefulWidget {
  final LunarData lunarData;

  const LunarInfoCard({Key? key, required this.lunarData}) : super(key: key);

  @override
  State<LunarInfoCard> createState() => _LunarInfoCardState();
}

class _LunarInfoCardState extends State<LunarInfoCard>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;

    return Column(
      children: [
        TabBar(
          controller: _tabController,
          labelColor: theme.colorScheme.primary,
          unselectedLabelColor: theme.colorScheme.onSurface.withOpacity(0.6),
          indicatorColor: theme.colorScheme.primary,
          tabs: const [
            Tab(text: '基本信息', icon: Icon(Icons.calendar_today)),
            Tab(text: '干支命理', icon: Icon(Icons.auto_awesome)),
            Tab(text: '宜忌', icon: Icon(Icons.list_alt)),
            Tab(text: '方位', icon: Icon(Icons.explore)),
          ],
        ),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: [
              _buildBasicInfoTab(context),
              _buildGanzhiTab(context),
              _buildYijiTab(context),
              _buildDirectionsTab(context),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildBasicInfoTab(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildInfoCard(
            context,
            title: '公历日期',
            content:
                '${widget.lunarData.gregorianYear}年${widget.lunarData.gregorianMonth}月${widget.lunarData.gregorianDay}日',
            subtitle: widget.lunarData.weekName,
            icon: Icons.today,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '农历日期',
            content:
                '${widget.lunarData.lunarYearChinese}年 ${widget.lunarData.lunarMonthChinese}${widget.lunarData.lunarDayChinese}',
            subtitle: widget.lunarData.lunarHourChinese,
            icon: Icons.event,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '生肖',
            content: widget.lunarData.animal,
            icon: Icons.pets,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '星座',
            content: widget.lunarData.constellation,
            icon: Icons.star,
          ),
          if (widget.lunarData.term.isNotEmpty) ...[
            const SizedBox(height: 16),
            _buildInfoCard(
              context,
              title: '节气',
              content: widget.lunarData.term,
              icon: Icons.wb_sunny,
            ),
          ],
          if (widget.lunarData.wuhou.isNotEmpty) ...[
            const SizedBox(height: 16),
            _buildInfoCard(
              context,
              title: '物候',
              content: widget.lunarData.wuhou,
              icon: Icons.eco,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildGanzhiTab(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildInfoCard(
            context,
            title: '年柱',
            content: widget.lunarData.ganzhiYear,
            subtitle:
                '五行: ${widget.lunarData.wuxingYear} | 颜色: ${widget.lunarData.colorYear}',
            icon: Icons.calendar_view_month,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '月柱',
            content: widget.lunarData.ganzhiMonth,
            subtitle:
                '五行: ${widget.lunarData.wuxingMonth} | 颜色: ${widget.lunarData.colorMonth}',
            icon: Icons.calendar_view_month,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '日柱',
            content: widget.lunarData.ganzhiDay,
            subtitle:
                '五行: ${widget.lunarData.wuxingDay} | 颜色: ${widget.lunarData.colorDay}',
            icon: Icons.calendar_view_day,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '时柱',
            content: widget.lunarData.ganzhiHour,
            subtitle:
                '五行: ${widget.lunarData.wuxingHour} | 颜色: ${widget.lunarData.colorHour}',
            icon: Icons.access_time,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '彭祖百忌',
            content: widget.lunarData.pengzugan,
            subtitle: widget.lunarData.pengzuzhi,
            icon: Icons.warning_amber,
          ),
          if (widget.lunarData.xiu.isNotEmpty) ...[
            const SizedBox(height: 16),
            _buildInfoCard(
              context,
              title: '二十八宿',
              content:
                  '${widget.lunarData.shou}${widget.lunarData.gong}${widget.lunarData.xiu} (${widget.lunarData.xiuLuck})',
              subtitle: '宿主: ${widget.lunarData.xiuAnimal}',
              icon: Icons.nights_stay,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildYijiTab(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildInfoCard(
            context,
            title: '今日宜',
            content: '',
            icon: Icons.thumb_up,
            customContent: _buildChipsGrid(
                context, widget.lunarData.yi, Colors.green.shade100),
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '今日忌',
            content: '',
            icon: Icons.thumb_down,
            customContent: _buildChipsGrid(
                context, widget.lunarData.ji, Colors.red.shade100),
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '吉神',
            content: '',
            icon: Icons.sentiment_very_satisfied,
            customContent: _buildChipsGrid(
                context, widget.lunarData.jishen, Colors.amber.shade100),
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '凶神',
            content: '',
            icon: Icons.sentiment_very_dissatisfied,
            customContent: _buildChipsGrid(
                context, widget.lunarData.xiongshen, Colors.purple.shade100),
          ),
        ],
      ),
    );
  }

  Widget _buildDirectionsTab(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildInfoCard(
            context,
            title: '财神方位',
            content: widget.lunarData.caishen,
            subtitle: widget.lunarData.caishenDesc,
            icon: Icons.attach_money,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '福神方位',
            content: widget.lunarData.fushen,
            subtitle: widget.lunarData.fushenDesc,
            icon: Icons.favorite,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '喜神方位',
            content: widget.lunarData.xishen,
            subtitle: widget.lunarData.xishenDesc,
            icon: Icons.mood,
          ),
          const SizedBox(height: 16),
          _buildInfoCard(
            context,
            title: '胎神',
            content: widget.lunarData.taishen,
            icon: Icons.child_care,
          ),
          const SizedBox(height: 24),
          _buildDirectionCompass(context),
        ],
      ),
    );
  }

  Widget _buildInfoCard(
    BuildContext context, {
    required String title,
    required String content,
    String? subtitle,
    required IconData icon,
    Widget? customContent,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onLongPress: content.isNotEmpty
            ? () {
                Clipboard.setData(ClipboardData(text: content));
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('已复制: $content')),
                );
              }
            : null,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(icon, color: Theme.of(context).colorScheme.primary),
                  const SizedBox(width: 8),
                  Text(
                    title,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              if (content.isNotEmpty) ...[
                const SizedBox(height: 8),
                Text(
                  content,
                  style: const TextStyle(fontSize: 18),
                ),
              ],
              if (subtitle != null && subtitle.isNotEmpty) ...[
                const SizedBox(height: 4),
                Text(
                  subtitle,
                  style: TextStyle(
                    fontSize: 14,
                    color: Theme.of(context)
                        .colorScheme
                        .onSurface
                        .withOpacity(0.6),
                  ),
                ),
              ],
              if (customContent != null) ...[
                const SizedBox(height: 8),
                customContent,
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildChipsGrid(
      BuildContext context, List<String> items, Color chipColor) {
    return Wrap(
      spacing: 8.0,
      runSpacing: 8.0,
      children: items.map((item) {
        return Chip(
          label: Text(item),
          backgroundColor: chipColor,
          labelStyle: TextStyle(
            color: chipColor.computeLuminance() > 0.5
                ? Colors.black87
                : Colors.white,
          ),
        );
      }).toList(),
    );
  }

  Widget _buildDirectionCompass(BuildContext context) {
    return Center(
      child: Container(
        width: 280,
        height: 280,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Theme.of(context).colorScheme.surface,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              spreadRadius: 2,
            ),
          ],
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 外圈
            Container(
              width: 260,
              height: 260,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
                  width: 2,
                ),
              ),
            ),
            // 内圈
            Container(
              width: 200,
              height: 200,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                  width: 1,
                ),
              ),
            ),
            // 中心点
            Container(
              width: 20,
              height: 20,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Theme.of(context).colorScheme.primary,
              ),
            ),
            // 方向标记
            ..._buildDirectionMarkers(context),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildDirectionMarkers(BuildContext context) {
    final directions = [
      {'label': '北', 'angle': 0.0, 'color': Colors.blue},
      {'label': '东北', 'angle': 45.0, 'color': Colors.teal},
      {'label': '东', 'angle': 90.0, 'color': Colors.green},
      {'label': '东南', 'angle': 135.0, 'color': Colors.lightGreen},
      {'label': '南', 'angle': 180.0, 'color': Colors.red},
      {'label': '西南', 'angle': 225.0, 'color': Colors.orange},
      {'label': '西', 'angle': 270.0, 'color': Colors.white},
      {'label': '西北', 'angle': 315.0, 'color': Colors.purple},
    ];

    return directions.map((dir) {
      final radians = (dir['angle'] as double) * (3.14159 / 180);
      final x = 120 * -sin(radians);
      final y = 120 * -cos(radians);

      return Positioned(
        left: 140 + x - 20,
        top: 140 + y - 20,
        child: Container(
          width: 40,
          height: 40,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: (dir['color'] as Color).withOpacity(0.2),
            border: Border.all(
              color: (dir['color'] as Color).withOpacity(0.5),
              width: 1,
            ),
          ),
          child: Text(
            dir['label'] as String,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Theme.of(context).colorScheme.onSurface,
            ),
          ),
        ),
      );
    }).toList();
  }
}

// 简单的三角函数，用于计算方位
double sin(double radians) {
  return radians < 0
      ? -(radians.abs() - radians.abs() * radians.abs() / 6)
      : radians - radians * radians / 6;
}

double cos(double radians) {
  return sin(radians + 3.14159 / 2);
}
